#!/usr/bin/env python3
"""
Build extensions paper from paper.md + tables → .docx
Uses pypandoc if available, otherwise falls back to pandoc CLI.
"""

import subprocess
from pathlib import Path

PROJECT_DIR = Path(__file__).resolve().parent.parent
PAPER_DIR = PROJECT_DIR / "paper"
TABLE_DIR = PROJECT_DIR / "output" / "tables"


def build():
    # Search for paper file in priority order
    candidates = [
        "extensions_paper_20260221_v6.md",
        "extensions_paper_20260221_v2.md",
        "paper.md",
    ]
    paper_md = None
    for c in candidates:
        p = PAPER_DIR / c
        if p.exists():
            paper_md = p
            break

    if paper_md is None:
        print(f"  ERROR: No paper.md found in {PAPER_DIR}")
        return

    output_docx = PAPER_DIR / "paper.docx"

    # Collect table files to append
    table_files = sorted(TABLE_DIR.glob("*.md"))
    print(f"  Paper: {paper_md}")
    print(f"  Tables: {len(table_files)} markdown files")

    # Build combined markdown
    combined = paper_md.read_text()
    for tf in table_files:
        combined += f"\n\n\\newpage\n\n"
        combined += tf.read_text()

    combined_path = PAPER_DIR / "paper_combined.md"
    combined_path.write_text(combined)

    # Convert to docx
    try:
        import pypandoc
        pypandoc.convert_file(
            str(combined_path), "docx",
            outputfile=str(output_docx),
            extra_args=["--standalone"]
        )
        print(f"  Output: {output_docx}")
    except ImportError:
        # Fallback to CLI
        try:
            subprocess.run(
                ["pandoc", str(combined_path), "-o", str(output_docx),
                 "--standalone"],
                check=True
            )
            print(f"  Output: {output_docx}")
        except FileNotFoundError:
            print("  WARNING: pandoc not found. Install with:")
            print("    pip install pypandoc")
            print("    or: apt install pandoc")
            print(f"  Combined markdown saved: {combined_path}")


if __name__ == "__main__":
    build()
